#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>

struct list
{
  struct list* next;
  int data;
};

struct list* head;
pthread_mutex_t lock;
pthread_cond_t cond;

void* producer(void*);
void* consumer(void*);

int main(int argc,char** argv)
{
  srand(time(NULL));
  pthread_mutex_init(&lock,NULL);
  pthread_cond_init(&cond,NULL);
  head = malloc(sizeof(struct list));
  head->next = NULL;

  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);

  pthread_t tid;
  pthread_create(&tid,NULL,producer,NULL);
  pthread_create(&tid,NULL,consumer,NULL);

  pthread_attr_destroy(&attr);
  pthread_cond_destroy(&cond);
  pthread_mutex_destroy(&lock);
  pthread_exit((void*)0);
}  

void* producer(void* num)
{
  struct list* new_node;
  pthread_t tid;
  while(1)
  {
    new_node = malloc(sizeof(struct list));
    new_node->data = rand()%1000;
    printf("produce is %d\n",new_node->data);

    pthread_mutex_lock(&lock);
    new_node->next = head->next;
    head->next = new_node;
    pthread_mutex_unlock(&lock);
    pthread_cond_signal(&cond);
    sleep(rand()%3);
  }
}
void* consumer(void* num)
{
  struct list* node;
  pthread_t tid;
  while(1)
  {
    pthread_mutex_lock(&lock);
    while(head->next == NULL)
    {
      pthread_cond_wait(&cond,&lock);
    }
    node = head->next;
    head->next = node->next;
    printf("consumer is %d\n",node->data);
    free(node);
    pthread_mutex_unlock(&lock);
    sleep(rand()%2);
  }
}
